﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using GameApplication.Helper;
using GameApplication.MiniGame.SimpleGame;
using Logic.MiniGameLogic;
using Logic.Units;

namespace GameApplication.MiniGame
{
    /// <summary>
    ///     Логика взаимодействия для FieldMiniGame.xaml
    /// </summary>
    public partial class FieldMiniGame : Page, IMiniGame
    {
        private UnitWpf _selectAfter;
        private bool _start;
        private ObservableCollection<UnitWpf> _defendersWpf;
        private ObservableCollection<UnitWpf> _troopsWpf;

        public FieldMiniGame()
        {
            InitializeComponent();
            Application.Current.Properties["TestGameFrame"] = TestGameFrame;
        }

        private void Win(object sender, RoutedEventArgs e)
        {
            OnEndGame(new List<IUnit>
            {
                new Infantry()
            });
        }

        private void Lose(object sender, RoutedEventArgs e)
        {
            OnEndGame(new List<IUnit>
            {
                new Infantry(UserState.Enemy)
            });
        }

        #region IMiniGame

        public event Action<List<IUnit>> EndGame;

        public void SetOpponents(List<IUnit> defenders, List<IUnit> troops)
        {
            _defendersWpf = defenders.First().State == UserState.Player
                ? defenders.ToWpf()
                : troops.ToWpf();

            _troopsWpf = defenders.First().State == UserState.Enemy
                ? defenders.ToWpf()
                : troops.ToWpf();

            ListBoxPalyer.ItemsSource = _defendersWpf;
            ListBoxEnemy.ItemsSource = _troopsWpf;
        }

        private void Update(bool win)
        {
        }

        public void SetWiner(List<IUnit> winer)
        {
            OnEndGame(winer);
        }

        public void Start()
        {
        }

        protected virtual void OnEndGame(List<IUnit> winer)
        {
            Action<List<IUnit>> handler = EndGame;
            if (handler != null) handler(winer);
        }

        #endregion

        private void Fight(object sender, RoutedEventArgs e)
        {
            _start = true;

            IUnit palyer = _defendersWpf.First().Unit;
            IUnit enemy = _troopsWpf.First().Unit;

            if (palyer == null || enemy == null) return;

            //TODO Инициализация простой игры
            //ISimpleGame game = new SliderMiniGame();
            ISimpleGame game = new StonePaperScissors();

            //game.SetOpponents(palyer, enemy);

            game.EndBattle += win =>
            {
                ///////////////////////////
                if (win)
                {
                    IUnit tmp = palyer;
                    palyer = enemy;
                    enemy = tmp;
                }
                palyer.GetDone(enemy);

                Frame frame = Application.Current.Properties["TestGameFrame"] as Frame;
                if (frame == null) return;
                frame.Visibility = Visibility.Collapsed;
                ///////////////////////////
                foreach (UnitWpf item in _defendersWpf.ToList().Where(item => item.ActualHp <= 0))
                {
                    _defendersWpf.Remove(item);
                }
                foreach (UnitWpf item in _troopsWpf.ToList().Where(item => item.ActualHp <= 0))
                {
                    _troopsWpf.Remove(item);
                }

                if (_defendersWpf.Count == 0 || _troopsWpf.Count == 0)
                {
                    OnEndGame(_defendersWpf.Count != 0
                        ? _defendersWpf.Select(item => item.Unit).ToList()
                        : _troopsWpf.Select(item => item.Unit).ToList());
                }

                ButtonStart.Visibility = Visibility.Visible;
            };

            ListBoxPalyer.IsEnabled = false;
            ListBoxEnemy.IsEnabled = false;

            ButtonStart.Visibility = Visibility.Collapsed;

            TestGameFrame.Content = game;
            TestGameFrame.Visibility = Visibility.Visible;
        }

        private void ListBoxPalyer_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_start) return;
            UnitWpf select = ListBoxPalyer.SelectedItem as UnitWpf;
            if (select == null) return;

            if (_selectAfter == null)
            {
                _selectAfter = select;
            }
            else
            {
                List<UnitWpf> old = _defendersWpf.ToList();

                _defendersWpf.Clear();

                foreach (UnitWpf element in old)
                {
                    UnitWpf item = element;
                    if (item == _selectAfter)
                    {
                        item = select;
                    }
                    else if (item == select)
                    {
                        item = _selectAfter;
                    }
                    _defendersWpf.Add(item);
                }
                ListBoxPalyer.ItemsSource = null;
                ListBoxPalyer.ItemsSource = _defendersWpf;
                _selectAfter = null;
            }
        }

        private void ListBoxPalyer_OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            _selectAfter = null;
        }
    }
}